<template>
    <div class=" w-[80%] mx-auto h-full">
        <div class=" flex items-center h-[85%]">
            <ProviderSelect :items="providers" v-model="currentProvider"></ProviderSelect>
        </div>
        <div class=" flex items-center h-[15%]">
            <MessageInput @create="createConversation" />
        </div>
    </div>
</template>

<script setup lang="ts">
import { ref, onMounted, computed } from 'vue'
import { db } from '../db'
import { useRouter } from 'vue-router'
import { useConversationStore } from '../stores/conversation';
import ProviderSelect from '../components/ProviderSelect.vue';
import MessageInput from '../components/MessageInput.vue';
import { ProviderProps } from '../types'

const router = useRouter()
const conversationStore = useConversationStore()
const currentProvider = ref('') //  选中模型（包含providerId/model)
const providers = ref<ProviderProps[]>([])
const modelInfo = computed(() => {
    const [providerId, selectedModel] = currentProvider.value.split('/')
    return {
        providerId: parseInt(providerId),
        selectedModel
    }
})
onMounted(async () => {
    // 初始化providers
    providers.value = await db.providers.toArray()
})
const createConversation = async (question: string) => {
    const { providerId, selectedModel } = modelInfo.value
    const currentDate = new Date().toISOString()
    // 记录conversation，生成conversationId
    const conversationId = await conversationStore.createConversation({
        title: question,
        selectedModel,
        createdAt: currentDate,
        updatedAt: currentDate,
        providerId
    })
    // 记录messages
    const newMessageId = await db.messages.add({
        content: question,
        type: 'question',
        conversationId,
        createdAt: currentDate,
        updatedAt: currentDate,
    })
    // 跳转路由，带查询参数
    router.push(`/conversation/${conversationId}?init=${newMessageId}`)
}
</script>